const Path = require('path')

function log(...args) {
  console.log('[useRouterPlugin]========> ', ...args)
}

function useRouterPlugin({ types: t }) {
  return {
    visitor: {
      ImportDeclaration(path) {
        const isISPFile = /(\\|\/)views\1srm\1isp\1/.test(this.filename)
        if (!isISPFile || path.node.source.value !== 'vue-router' || this.filename.split(Path.sep).pop().match(/useIspRouter/i)) {
          return
        }
        log('filename:', this.filename)
        const specifiers = path.node.specifiers || []
        // del userRouter
        path.node.specifiers = specifiers.filter(sp => sp.imported.name !== 'useRouter')
        // import { useRouter} from '@/useIspRouter'
        const newSpecifier = t.importSpecifier(t.identifier('useRouter'), t.stringLiteral('useRouter'))
        const importDeclaration = t.importDeclaration([newSpecifier], t.stringLiteral('@/useIspRouter'))
        path.insertAfter(importDeclaration)
      }

    }
  }
}


module.exports = useRouterPlugin

